import Types from "../Types";
import DataStore, {FLAG_STORAGE} from "../../expand/dao/DataStore";
import {handleData} from '../ActionUtil';

/**
 * Popular刷新的异步action创建函数(异步action创建依赖于redux-thunk)
 * @param storeName
 * @param url
 * @param pageSize
 * @returns {Function}
 */
export function onRefreshPopular(storeName, url, pageSize) {
  return dispatch => {
    dispatch({ // 首先开启加载中状态
      type: Types.POPULAR_REFRESH,
      storeName: storeName
    });
    let dataStore = new DataStore(); // 建立数据流对象
    dataStore.fetchData(url, FLAG_STORAGE.flag_popular) // 开始请求数据
      .then(data => {
        handleData(Types.POPULAR_REFRESH_SUCCESS, dispatch, storeName, data, pageSize) // 请求成功
      })
      .catch(error => {
        dispatch({ // 请求失败，发送action POPULAR_REFRESH_FAILURE
          type: Types.POPULAR_REFRESH_FAILURE,
          storeName,
          error
        })
      })
  }
}

/**
 * Popular加载更多数据
 * @param storeName
 * @param pageIndex
 * @param pageSize
 * @param allItems
 * @param callBack
 * @returns {Function}
 */
export function onLoadMorePopular(storeName, pageIndex, pageSize, allItems = [], callBack) {
  return dispatch => {
    setTimeout(() => {
      if (pageIndex * pageSize >= allItems.length) { // 已加载全部数据
        if (typeof callBack === 'function') {
          callBack('no more')
        }
        dispatch({
          type: Types.POPULAR_LOAD_MORE_FAILURE,
          storeName,
          pageIndex: pageIndex > 1 ? pageIndex - 1 : pageIndex,
          items: allItems,
          error: 'no more'
        })
      } else {
        let max = pageIndex * pageSize > allItems.length ? allItems.length : pageIndex * pageSize;
        dispatch({
          type: Types.POPULAR_LOAD_MORE_SUCCESS,
          storeName,
          pageIndex,
          items: allItems.slice(0, max)
        })
      }
    }, 500)
  }
}